/*
 *   Licensed to the Apache Software Foundation (ASF) under one
 *   or more contributor license agreements.  See the NOTICE file
 *   distributed with this work for additional information
 *   regarding copyright ownership.  The ASF licenses this file
 *   to you under the Apache License, Version 2.0 (the
 *   "License"); you may not use this file except in compliance
 *   with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */
package net.sk.mina.imagine.codec;

import net.sk.mina.imagine.FrameHeader;
import net.sk.mina.imagine.ImageResponse;

import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * a decoder for {@link ImageResponse} objects 
 *
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */

public class ImageResponseDecoder extends CumulativeProtocolDecoder {

    private static final String DECODER_STATE_KEY = ImageResponseDecoder.class.getName() + ".STATE";

    public static final int MAX_IMAGE_SIZE = 5 * 1024 * 1024;

    private static class DecoderState {
    	FrameHeader fh;
        BufferedImage image1;
        long buflen = FrameHeader.LEN;
        boolean bfh = true;
    }

    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
        if (decoderState == null) {
            decoderState = new DecoderState();
            session.setAttribute(DECODER_STATE_KEY, decoderState);
        }
        try{
        // try to read first image
        if (in.remaining()>= decoderState.buflen) {
        	if(decoderState.bfh){
        		FrameHeader fh = readFrameHeader(in);
        		decoderState.fh =fh;
        		if(fh.getFrame_type()!=FrameHeader.FRAME_TYPE_HEART){
        			decoderState.bfh = false;
        			decoderState.buflen = fh.getLen();
        			return false;
        		}else{
                    ImageResponse imageResponse = new ImageResponse(decoderState.fh,null);
                    out.write(imageResponse);
        			return true;
        		}
        	}else{
        		decoderState.image1 = readImage(in,decoderState.buflen);
        		decoderState.bfh = true;
                ImageResponse imageResponse = new ImageResponse(decoderState.fh,decoderState.image1);
                out.write(imageResponse);
        		return true;
        	}
        } else {
            // not enough data available to read first image
            return false;
        }
        }catch(Exception e){
        	e.printStackTrace();
        	return false;
        }
    }

    private FrameHeader readFrameHeader(IoBuffer in){
    	FrameHeader fh = new FrameHeader();
    	fh.decode(in);
    	return fh;
    }
    private BufferedImage readImage(IoBuffer in,long len) throws IOException {
        //int length = in.getInt();
        byte[] bytes = new byte[(int)len];
        in.get(bytes);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        return ImageIO.read(bais);
    }
    
}
